<?php
/**
 * Prints out a list of value, from csv format, or to csv format
 *
 * @key required keys '2,3'(csv_string)|'__ALL__'
 * @key required values $array
 * @key optional separator
 * @key optional_system assign assign the output as an array to this variable
 * @key optional else 'nothing to csv'
 * @key optional wrap '<li>%s</li>'
 * @key optional key = val => 1 = 'option 1' 2 = 'option 2' => see examples
 
 * @tag codeall_csv_values
 * @date 2006.03.14
 * @author CodeAll
 * @version 1.0.20060314
 
 * @param array
 * @param Smarty
 
 * @return string
 * @uses smarty_function_escape_special_chars()
 * @usage $smarty->register_function("codeall_csv_values", "smarty_function_codeall_csv_values")
 */
/* eg.
 * {codeall_csv_values keys='2,3' 1='this is 1' 2='this is 2' 3='this is 3' 4='this is 4' separator=', ' else='nothing to loop'}
 * {codeall_csv_values keys='2,3' values='this is 1,this is 2,this is 3,this is 4' separator=', ' else='nothing to loop'}
 * {codeall_csv_values keys='__ALL__' values='option 1,option 2,option 3'}
*/
function smarty_function_codeall_csv_values($params, &$smarty)
{
    require_once $smarty->_get_plugin_filepath('shared','escape_special_chars');

	$keys = null;
    $values = null;
    $separator = ', ';
    $else = '';
    $wrap = '%s';

    foreach($params as $_key => $_val) {
        switch($_key) {
            case 'separator':
            case 'else':
            case 'wrap':
                $$_key = $_val;
                break;

            case 'values':
            	if (is_array($_val)) {
            		$$_key = $_val;
            	}
            	else if ($_val != '') {
	                $$_key = explode(',', $_val);
	        	}
                break;
			
            case 'keys':
            	if ($_val == '__ALL__') {
            		$$_key = '__ALL__';
            	}
            	else if ($_val != '') {
	                $$_key = explode(',', $_val);
	        	}
                break;
			
			# to ommit
            case 'assign':
                break;

            default:
                if(!is_array($_val)) {
                	$values[$_key] = smarty_function_escape_special_chars($_val);
                } else {
                    $smarty->trigger_error("codeall_csv_values: extra attribute '$_key' cannot be an array", E_USER_NOTICE);
                }
                break;
        }
    }

    if (!isset($values)) {
        return ''; /* raise error here? */
	}
	
    $_html_result = array();

    if (isset($keys)) {
    	if ($keys == '__ALL__') {
		    foreach ($values as $_key=>$_val) {
		        $_html_result[] = sprintf($wrap, $_val);
			}
    	}
    	else {
		    foreach ($keys as $_key=>$_val) {
		        $_html_result[] = sprintf($wrap, $values[$_val]);
			}
		}
	}
	else {
		$_html_result[] = $else;
	}
	
    if(!empty($params['assign'])) {
        $smarty->assign($params['assign'], $_html_result);
    } else {
        return implode($separator,$_html_result);
    }
}
?>